<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="600px" @ok="handleSubmit" showFooter destroyOnClose>
    <BasicForm @register="registerForm">
      <template #pageUrl="{ model, field }">
        <a-input v-model:value="model[field]" readOnly placeholder="请选择地址" @click="handleOpenSelectUrl" />
        <div style="margin-top: 5px" class="text-color-call-out">{{ model["name"] }}</div>
      </template>
    </BasicForm>
  </BasicDrawer>
  <SelectLink @register="registerModal" @change="handleSelectLink" />
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { inputFormSchemas } from "./data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateMobileMenu, getMobileMenu } from "/@/api/sys/mobileMenu"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { SelectLink } from "/@/components/BizAppSelectLink/index"
  import { useModal } from "/@/components/Modal"
  import { ColEx } from "/@/components/Form/src/types"
  const { createMessage } = useMessage()

  const [registerModal, { openModal }] = useModal()
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const record = ref<any>({})

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate

      if (unref(isUpdate)) {
        record.value = (await getMobileMenu({ id: data.record.id })) || {}
      }

      setFieldsValue({
        ...record.value,
      })
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增移动端菜单" : "编辑移动端菜单"))

  async function handleSubmit() {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })

      await saveOrUpdateMobileMenu({ ...values }, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const handleOpenSelectUrl = () => {
    openModal(true, {})
  }

  const handleSelectLink = (data) => {
    setFieldsValue({
      pageUrl: data.pageUrl,
      name: data.name,
    })
  }
</script>
